﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;

namespace Common
{
    public class Auxiliary
    {

        [DllImport("shfolder.dll", CharSet = CharSet.Auto)]
        private static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);
        private const int MAX_PATH = 260;
        private const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019;
        /// <summary>
        /// 获取所有用户桌面路径
        /// </summary>
        /// <returns></returns>
        public string GetAllUsersDesktopFolderPath()
        {
            StringBuilder sbPath = new StringBuilder(MAX_PATH);
            SHGetFolderPath(IntPtr.Zero, CSIDL_COMMON_DESKTOPDIRECTORY, IntPtr.Zero, 0, sbPath);
            return sbPath.ToString();
        }

        /// <summary>
        /// 获取当前用户桌面路径
        /// </summary>
        /// <returns></returns>
        public string GetUsersDesktopFolderPath()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        }

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string defVal, StringBuilder retVal, int size, string filePath);

        /// <summary>    
        /// 读取INI文件    
        /// </summary>    
        /// <param name="section">项目名称(如 [section] )</param>    
        /// <param name="skey">键</param>   
        /// <param name="path">路径</param> 
        public static string IniReadValue(string section, string skey, string path)
        {
            StringBuilder temp = new StringBuilder(500);
            int i = GetPrivateProfileString(section, skey, "", temp, 500, path);
            return temp.ToString();
        }

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        /// <summary>
        /// 写INI文件
        /// </summary>
        /// <param name="section">段落</param>
        /// <param name="key">键</param>
        /// <param name="iValue">值</param>
        /// <param name="path">路径</param>
        public static void IniWriteValue(string section, string key, string iValue, string path)
        {
            WritePrivateProfileString(section, key, iValue, path);
        }

        public enum ShowWindowCommands : int
        {

            SW_HIDE = 0,
            SW_SHOWNORMAL = 1,    //用最近的大小和位置显示，激活
            SW_NORMAL = 1,
            SW_SHOWMINIMIZED = 2,
            SW_SHOWMAXIMIZED = 3,
            SW_MAXIMIZE = 3,
            SW_SHOWNOACTIVATE = 4,
            SW_SHOW = 5,
            SW_MINIMIZE = 6,
            SW_SHOWMINNOACTIVE = 7,
            SW_SHOWNA = 8,
            SW_RESTORE = 9,
            SW_SHOWDEFAULT = 10,
            SW_MAX = 10
        }
        [DllImport("shell32.dll")]
        public static extern IntPtr ShellExecute(IntPtr hwnd, string lpszOp, string lpszFile, string lpszParams, string lpszDir, ShowWindowCommands FsShowCmd);
        [DllImport("kernel32")]
        public static extern IntPtr WaitForSingleObject(IntPtr hHandle, IntPtr dwMilliseconds);
        public void ShellEx(string FileName, string arg, bool wait)
        {
            IntPtr Handle = ShellExecute(IntPtr.Zero, "open", FileName, arg, null, ShowWindowCommands.SW_SHOWMINNOACTIVE);
            if (wait == true)
                WaitForSingleObject(Handle, IntPtr.Zero);
        }

        [DllImport("user32.dll")]
        static extern bool ExitWindowsEx(int uFlags, int dwReserved);
        public void ResetComputer(int type)
        {
            if (type == 0)
                ExitWindowsEx(ExitWindows.EWX_FORCE, 0);
            if (type == 1)
                ExitWindowsEx(ExitWindows.EWX_SHUTDOWN, 0);
        }

        /// <summary>  
        /// 时间戳转为C#格式时间  
        /// </summary>  
        /// <param name="timeStamp">Unix时间戳格式</param>  
        /// <returns>C#格式时间</returns>  
        public DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }


        /// <summary>  
        /// DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time"> DateTime时间格式</param>  
        /// <returns>Unix时间戳格式</returns>  
        public int ConvertDateTimeInt(DateTime time)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// 获取系统时间
        /// </summary>
        /// <param name="st"></param>
        [DllImport("Kernel32.dll")]

        public static extern void GetLocalTime(SystemTime st);

        /// <summary>
        /// 设置系统时间
        /// </summary>
        /// <param name="st"></param>
        [DllImport("Kernel32.dll")]

        public static extern void SetLocalTime(SystemTime st);



        #region DES 加密解密

        /// <summary>
        /// DES 加密
        /// </summary>
        public string Des(string value, string keyVal, string ivVal)
        {
            try
            {
                byte[] data = Encoding.UTF8.GetBytes(value);
                var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(keyVal.Length > 8 ? keyVal.Substring(0, 8) : keyVal), IV = Encoding.ASCII.GetBytes(ivVal.Length > 8 ? ivVal.Substring(0, 8) : ivVal) };
                var desencrypt = des.CreateEncryptor();
                byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
                return BitConverter.ToString(result);
            }
            catch { return ""; }
        }

        /// <summary>
        /// DES 解密
        /// </summary>
        public string UnDes(string value, string keyVal, string ivVal)
        {
            try
            {
                string[] sInput = value.Split("-".ToCharArray());
                byte[] data = new byte[sInput.Length];
                for (int i = 0; i < sInput.Length; i++)
                {
                    data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
                }
                var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(keyVal.Length > 8 ? keyVal.Substring(0, 8) : keyVal), IV = Encoding.ASCII.GetBytes(ivVal.Length > 8 ? ivVal.Substring(0, 8) : ivVal) };
                var desencrypt = des.CreateDecryptor();
                byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
                return Encoding.UTF8.GetString(result);
            }
            catch { return ""; }
        }

        #endregion

        public static string GetSubString(string front, string back, string str)
        {
            int i = str.IndexOf(front, StringComparison.Ordinal) + front.Length;
            if (i <= 0)
                return "";
            int l = str.IndexOf(back, i);
            return str.Substring(i, l - i);
        }

        public static string GetFileMD5(string filePath)
        {
            FileStream file = new FileStream(filePath, FileMode.Open);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(file);
            file.Close();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
    }

    public class ExitWindows
    {
        /// <summary>
        /// 关闭所有进程，然后注销用户
        /// </summary>
        public const int EWX_LOGOFF = 0x00000000;

        /// <summary>
        /// 关闭系统，安全地关闭电源
        /// </summary>
        public const int EWX_SHUTDOWN = 0x00000001;

        /// <summary>
        /// 关闭系统，然后重新启动系统。
        /// </summary>
        public const int EWX_REBOOT = 0x00000002;

        /// <summary>
        /// 强制终止进程
        /// </summary>
        public const int EWX_FORCE = 0x00000004;

        /// <summary>
        /// 关闭系统并关闭电源。该系统必须支持断电
        /// </summary>
        public const int EWX_POWEROFF = 0x00000008;

        public const int EWX_FORCEIFHUNG = 0x00000010;
    }

    public class SystemTime

    {

        public ushort vYear;

        public ushort vMonth;

        public ushort vDayOfWeek;

        public ushort vDay;

        public ushort vHour;

        public ushort vMinute;

        public ushort vSecond;

    }
}
